#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

class pthreadMutex
{
private:
    int tickets;
    pthread_mutex_t mutex;

public:
    pthreadMutex()
    :tickets(10000)
    {
        pthread_mutex_init(&mutex, NULL);
    }

    bool getTickets()
    {
        bool tmp = true;
        pthread_mutex_lock(&mutex);

        // 临界区
        if(tickets > 0)
        {
            usleep(1000);
            std::cout << "我是 [" << pthread_self() << "] 我抢到的票是" << tickets << std::endl;
            tickets--;
            printf("");
        }
        else
        {
            tmp = false;
            std::cout << "票已经抢完了" << std::endl;
        }
        pthread_mutex_unlock(&mutex);
        return tmp;
    }

    ~pthreadMutex()
    {
        pthread_mutex_destroy(&mutex);
    }
};

pthreadMutex obj;

void* pthreadRun(void* args)
{
    bool isVaild = true;
    while(isVaild)
    {
        isVaild = obj.getTickets(); 
    }
    return (void*)123;
}

#define NUM 5

int main()
{
    pthread_t tid[NUM];
    for(int i = 0; i < NUM; ++i)
    {
        pthread_create(tid + i, NULL, pthreadRun, (void*)i);
    }

    for(int i = 0; i < NUM; ++i)
        pthread_join(tid[i], NULL);
    return 0;
}